package com.example.hibernate.demo.controller;

import com.example.hibernate.demo.entity.*;
import com.example.hibernate.demo.repository.*;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.RequiredArgsConstructor;
import org.hibernate.Session;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 这个控制器展示了Hibernate的实体操作和关系管理
 */
@RestController
@RequestMapping("/api/hibernate-examples")
@RequiredArgsConstructor
public class HibernateExamplesController3 {

    @PersistenceContext
    private EntityManager entityManager;
    
    private final DepartmentRepository departmentRepository;
    private final EmployeeRepository employeeRepository;
    private final ProjectRepository projectRepository;
    
    /**
     * 展示实体状态和生命周期
     */
    @GetMapping("/entity-lifecycle-demo")
    @Transactional
    public ResponseEntity<Map<String, String>> entityLifecycleDemo() {
        Map<String, String> result = new HashMap<>();
        
        // 瞬时状态 (Transient)
        Employee newEmployee = Employee.builder()
                .firstName("Alice")
                .lastName("Wonder")
                .email("alice.wonder@example.com")
                .salary(new BigDecimal("78000.00"))
                .status(Employee.EmployeeStatus.ACTIVE)
                .build();
        result.put("transientState", "Created employee: " + newEmployee.getFirstName());
        
        // 持久状态 (Persistent)
        Department dept = departmentRepository.findById(1L).orElse(null);
        if (dept != null) {
            newEmployee.setDepartment(dept);
            employeeRepository.save(newEmployee);
            result.put("persistentState", "Saved employee with ID: " + newEmployee.getId());
            
            // 修改持久状态的实体
            newEmployee.setSalary(new BigDecimal("80000.00"));
            // 不需要显式调用save，事务提交时会自动更新
            result.put("dirtyChecking", "Updated salary to: " + newEmployee.getSalary());
        }
        
        // 分离状态 (Detached)
        entityManager.detach(newEmployee);
        newEmployee.setSalary(new BigDecimal("82000.00"));
        result.put("detachedState", "Changed salary in detached state: " + newEmployee.getSalary() + " (won't be saved)");
        
        // 重新附加 (Reattach)
        newEmployee = entityManager.merge(newEmployee);
        result.put("reattachedState", "Reattached employee with salary: " + newEmployee.getSalary());
        
        // 删除状态 (Removed)
        entityManager.remove(newEmployee);
        result.put("removedState", "Removed employee with ID: " + newEmployee.getId());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 展示关系管理
     */
    @GetMapping("/relationship-demo")
    @Transactional
    public ResponseEntity<Map<String, String>> relationshipDemo() {
        Map<String, String> result = new HashMap<>();
        
        // 创建新部门
        Department newDept = Department.builder()
                .name("Research & Development")
                .description("Product innovation and research")
                .build();
        departmentRepository.save(newDept);
        result.put("newDepartment", "Created department: " + newDept.getName());
        
        // 创建新员工并关联到部门
        Employee newEmployee = Employee.builder()
                .firstName("Charlie")
                .lastName("Brown")
                .email("charlie.brown@example.com")
                .salary(new BigDecimal("90000.00"))
                .status(Employee.EmployeeStatus.ACTIVE)
                .department(newDept)
                .build();
        employeeRepository.save(newEmployee);
        result.put("employeeDepartment", "Employee " + newEmployee.getFirstName() + 
                " assigned to department: " + newEmployee.getDepartment().getName());
        
        // 创建新项目
        Project newProject = Project.builder()
                .name("AI Research")
                .description("Artificial Intelligence Research Project")
                .startDate(LocalDate.now())
                .endDate(LocalDate.now().plusMonths(6))
                .status(Project.ProjectStatus.PLANNING)
                .build();
        projectRepository.save(newProject);
        result.put("newProject", "Created project: " + newProject.getName());
        
        // 将员工分配到项目 (多对多关系)
        newEmployee.addProject(newProject);
        employeeRepository.save(newEmployee);
        result.put("employeeProject", "Employee " + newEmployee.getFirstName() + 
                " assigned to project: " + newProject.getName());
        
        // 创建员工详情 (一对一关系)
        EmployeeDetail detail = EmployeeDetail.builder()
                .address("789 Pine St, Somewhere")
                .phoneNumber("555-9876")
                .birthDate(LocalDate.of(1988, 3, 15))
                .hireDate(LocalDate.now())
                .emergencyContact(new EmployeeDetail.EmergencyContact("Sarah Brown", "Spouse", "555-4567"))
                .employee(newEmployee)
                .build();
        newEmployee.setEmployeeDetail(detail);
        employeeRepository.save(newEmployee);
        result.put("employeeDetail", "Added details for employee: " + 
                newEmployee.getFirstName() + ", Phone: " + newEmployee.getEmployeeDetail().getPhoneNumber());
        
        return ResponseEntity.ok(result);
    }
}